package com.xixi.core.rpc.proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: zxh
 * @date: 2024/8/21 21:27
 * @description: Mock服务代理
 */
@Slf4j
public class MockServiceProxy implements InvocationHandler {

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// 根据方法的返回值类型，生成特定的默认值对象
		Class<?> methodReturnType = method.getReturnType();
		log.info("mock invoke {}", method.getName());
		return getDefaultObject(methodReturnType);
	}

	/**
	 * 生成指定类型的默认值对象
	 * @param type 默认值类型
	 * @return 返回默认值
	 */
	private Object getDefaultObject(Class<?> type) {
		// 基本类型
		if (type.isPrimitive()) {
			if (type == boolean.class) {
				return false;
			} else if (type == short.class) {
				return (short) 0;
			} else if (type == int.class) {
				return 0;
			} else if (type == long.class) {
				return 0L;
			}
		}
		// 对象类型
		try {
			return type.getDeclaredConstructor().newInstance();
		} catch (InvocationTargetException |
		         InstantiationException |
		         IllegalAccessException |
		         NoSuchMethodException e) {
			return null;
		}
	}
}
